using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;

namespace Pikapika.Models
{
    internal class ChapterContentStore : IChapterContentStore
    {

        private static readonly ChapterContentStore _instance = new ChapterContentStore();

        private static readonly string PATH_FORMAT = "~/Upload/Chapters/{0}/{1}/{2}";

        private ChapterContentStore()
        {

        }

        public static ChapterContentStore Instance
        {
            get
            {
                return _instance;
            }
        }


        private static string GetFilePath(NovelChapter ch)
        {
            string filePath;
            var context = HttpContext.Current;
            filePath = context.Server.MapPath(string.Format(PATH_FORMAT, ch.NovelId, ch.NovelVolumeId, ch.Id));
            return filePath;
        }

        #region IChapterContentStore Members

        public string LoadChapterContent(NovelChapter ch)
        {
            if (ch == null)
                throw new ArgumentNullException("ch", "ch is null.");

            string filePath = GetFilePath(ch);
            if (!File.Exists(filePath))
            {
                return string.Empty;
            }
            return File.ReadAllText(filePath);
        }

        public void SaveChapterContent(NovelChapter ch)
        {
            if (ch == null)
                throw new ArgumentNullException("ch", "ch is null.");


            string filePath = GetFilePath(ch);
            var fileDirectory = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(fileDirectory))
            {
                Directory.CreateDirectory(fileDirectory);
            }
            File.WriteAllText(filePath, ch.ChapterContent);
        }

        #endregion
    }
}
